package com.ktc.service;

import com.ktc.dao.SpitDao;
import com.ktc.search.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.Date;
import java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;


    public void save(Spit spit) {

        spit.setId(idWorker.nextId() + "");
        spit.setPublishtime(new Date());//发布日期
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setState("1");//状态
        spit.setComment(0);//回复数


        // 你到底是吐槽还是评论啊
        if (spit.getParentid() != null && !spit.getParentid().equals("")) {
            // 肯定是评论

            // 对应的那个吐槽的回复数+1
            Query query=new Query();
            // 我的parentid就是别人的id
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));

            Update update=new Update();
            update.inc("comment",1);

            mongoTemplate.updateFirst(query,update,"spit");
        }


        spitDao.save(spit);

    }

    public void delete(String id) {
        spitDao.deleteById(id);
    }

    public void update(Spit spit) {
        spitDao.save(spit);
    }

    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    public Spit findById(String id) {
        return spitDao.findById(id).get();
    }

    public Page<Spit> comment(String parentid, Integer page, Integer size) {

        // ?

        return spitDao.findByParentid(parentid, PageRequest.of(page - 1, size));
    }

    public void thumbup(String spitid) {

/*        Spit spit = spitDao.findById(spitid).get();

        spit.setThumbup(spit.getThumbup()+1);

        spitDao.save(spit);*/

        // Bson  db.spit.update({_id:spitid},{$inc:{thumbup:NumberInt(1)}})

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitid));

        Update update = new Update();
        update.inc("thumbup", 1);

        mongoTemplate.updateFirst(query, update, "spit");
    }

    public void delThumbup(String spitid) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitid));

        Update update = new Update();
        update.inc("thumbup", -1);

        mongoTemplate.updateFirst(query, update, "spit");
    }
}
